" File: extended.vim
" Version: 1.0.0 
" Maintainer: Sang Yang (yssh28@gmail.com) 
" License: This program is free software.
"
" All extended plugin is setted in the script according to personal demand 
" for Vim.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" SECTION: Initialization {{{1
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Check if the script has been loaded
if exists('g:loaded_extended')
    finish
endif
let g:loaded_extended = 1

" set the 'cpoptions' option to its Vim default value and restore it later.
" That will allow the use of line-continuation
let s:save_cpo = &cpoptions
set cpoptions&vim

" The path of the directory of the script itself
let s:basic_path = fnamemodify(globpath(&runtimepath, 'extended.vim'), ':p:h') . '/'

" These log functions used log running message in the script, even more
" log extenal shell by the way of redirect to the logging file.
let s:log_path = s:basic_path . 'common/extend.log'

" lines must be a list, and  working with file *possibly* containing trailing newline
function AppendToFile(file, lines)
    let fcontents=readfile(a:file, 'b')
    if !empty(fcontents) && empty(fcontents[-1])
        call remove(fcontents, -1)
    endif
    call writefile(fcontents+a:lines, a:file, 'b')
endfunction

function LogPrint(...)
    if filewritable(s:log_path)
        let line =  '>>' . strftime('%Y-%m-%d %H:%M:%S') . ' ' 
            \ . expand('%:p:S') . ':' . line('.') . ' '
        for arg in a:000
            let line .= arg . ' '
        endfor
        let lines = []
        call insert(lines, line, 0)
        call AppendToFile(s:log_path, lines)
    endif
endfunction

function LogExecute(cmd)
    let command  = a:cmd
    if filewritable(s:log_path)
        call LogPrint(command)
        if command[0] == '!'
            let command .= ' 1>>' . s:log_path . ' 2>&1'
        endif
    endif
    echomsg command
    execute(command)
endfunction


" SECTION: vim-plug <plugin> {{{1
" Author: https://github.com/junegunn/vim-plug 
" A minimalist Vim plugin manager.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let s:plug_path = s:basic_path . 'autoload/plug.vim'
let s:plug_scripts_path = s:basic_path . 'bundle'

if !filereadable(s:plug_path)
    call LogExecute('!curl -fLo ' . s:plug_path . ' --create-dirs 
        \https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim')
endif

if filereadable(s:plug_path)
    " Specify a directory for plugins
    silent! call plug#begin(s:plug_scripts_path)

    "Plug '~/.vim/bundle/winmanager'
    "Plug '~/.vim/bundle/CSApprox'
    "Plug '~/.vim/bundle/c-support'
    "Plug '~/.vim/bundle/perl-support'
    Plug '~/.vim/bundle/bash-support'
    Plug '~/.vim/bundle/nerdtree'
    Plug '~/.vim/bundle/omnicppcomplete'
    Plug '~/.vim/bundle/supertab'
    Plug '~/.vim/bundle/snipMate'
    Plug '~/.vim/bundle/pydiction'
    Plug '~/.vim/bundle/vcscommand'
    Plug '~/.vim/bundle/xmledit'
    Plug '~/.vim/bundle/emmet'
    Plug '~/.vim/bundle/easy-align'
    Plug '~/.vim/bundle/syntastic'
    Plug '~/.vim/bundle/ctrlp'
    "Plug 'https://github.com/plasticboy/vim-markdown.git'
    "Plug 'https://github.com/tpope/vim-markdown.git'

    " List ends here. Plugins become visible to Vim after this call.
    call plug#end()
endif

function <SID>PlugHelptags()
    let rtp_list = split(&runtimepath, ',')
    for path in rtp_list
        if '/' != path[strlen(path)-1]
            let path .= '/'
        endif
        let doc_path = path . 'doc/'
        if -1 == stridx(doc_path, s:basic_path) || !isdirectory(doc_path)
            continue
        endif
        call delete(doc_path . 'tags')
        call LogExecute("helptags " . doc_path)
    endfor
endfunction

command PlugHelptags call <SID>PlugHelptags()


" SECTION: Ctags <program> {{{1
" Author: http://ctags.sourceforge.net
" Ctags generates an index (or tag) file of language objects found in source
" files that allows these items to be quickly and easily located by a text
" editor or other utility.
"
" A tag is an identifier that appears in a "tags" file.  It is a sort of label
" that can be jumped to.  For example: In C programs each function name can be
" used as a tag.  The "tags" file has to be generated by a program like ctags,
" before the tag commands can be used.
" 1): Jump to a tag
"   :[count]tag {ident} Jump to the definition of {ident},
"   g<LeftMouse>
"   <C-LeftMouse>
"   CTRL-]           Jump to the definition of the keyword under the cursor.
"   {Visual}CTRL-]   Jump to the definition of the text that is highlighted.
" 2): Tag stack
"   g<RightMouse>
"   <C-RightMouse>
"   CTRL-T           Jump to [count] older entry in the tag stack
"   :[count]pop      Jump to [count] older entry in tag stack (default 1).
"   :[count]tag      Jump to [count] newer entry in tag stack (default 1).
"   :tags            Show the contents of the tag stack.
" 3): Tag match list
"   :tselect [ident]    List the tags that match [ident]
"   g]
"   {Visual}g]          Like CTRL-], but use ":tselect" instead of ":tag"
"   :tjump [ident]      Like ":tselect", but jump to the tag directly 
"                       when there is only one match
"   g CTRL-]
"   {Visual}g CTRL-]    Like CTRL-], but use ":tjump" instead of ":tag"
"   :[count]tnext       Jump to [count] next matching tag (default 1)
"   :[count]tNext
"   :[count]tprevious   Jump to [count] previous matching tag (default 1)
"   :[count]trewind
"   :[count]tfirst      Jump to first matching tag
"   :tlast              Jump to last matching tag
"   :ltag [ident]       Jump to tag [ident] and add the matching tags to
"                       a new location list for the current window
" 4): Tags details
"   When the argument starts with '/', it is used as a pattern.
"   Examples
"       :tag /^get
"       jumps to the tag that starts with "get" and has the highest priority
" 5): Tags file format
"   A tags file can be created with an external command, for example "ctags".
" 6): Include file searches
"   These commands look for a string in the current file and in all
"   encountered included files (recursively).  This can be used to
"   find the definition of a variable, function or macro.
"   The commands that start with "[" start searching from the start
"   of the current file, that start with "]" start at the current
"   cursor position.
"   [i
"   ]i            (start at the current cursor position)
"   :[range]isearch [count] [/]pattern[/]
"                 Display the first line that contains the keyword under
"                 the cursor
"   [I
"   ]I            (start at the current cursor position)
"   :[range]ilist [/]pattern[/]
"                 Display all lines that contain the keyword under the
"                 cursor
"   [ CTRL-I
"   ] CTRL-I      (start at the current cursor position)
"   :[range]ijump [count] [/]pattern[/]
"                 Jump to the first line that contains the keyword under
"                 the cursor
"   CTRL-W CTRL-I
"   CTRL-W i
"   :[range]isplit [count] [/]pattern[/]
"                 Open a new window, with the cursor on the first line
"                 that contains the keyword under the cursor.
"   [d
"   ]d            (start at the current cursor position)
"   :[range]dsearch [count] [/]string[/]
"                 Display the first macro definition that contains the
"                 macro under the cursor
"   [D
"   ]D            (start at the current cursor position)
"   :[range]dlist [/]string[/]
"                 Display all macro definitions that contain the macro
"                 under the cursor
"   [ CTRL-D
"   ] CTRL-D      (start at the current cursor position)
"   :[range]djump [count] [/]string[/]
"                 Jump to the first macro definition that contains the
"                 keyword under the cursor
"   CTRL-W CTRL-D
"   CTRL-W d
"   :[range]dsplit [count] [/]string[/]
"                 Open a new window, with the cursor on the first macro
"                 definition line that contains the keyword under the cursor
"   :checkpath    List all the included files that could not be found
"   :checkpath!   List all the included files
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Add filename for the tag command, separated by spaces or commas.
let s:tags_path = s:basic_path . 'common/tags'
let &tags .= ',./.tags;,.tags,' . s:tags_path

" Create common tags in a specifically position
function <SID>TagsCommon(...)
    let cmd = "!ctags -I __THROW -I __attribute_pure__
        \ -I __nonnull -I __attribute__ --file-scope=yes
        \ --langmap=c:+.h --languages=c,c++ --links=yes
        \ --c-kinds=+p --c++-kinds=+p --fields=+iaS --extra=+q  -f "
        \ . s:tags_path .
        \ "
        \ /usr/include/*
        \ /usr/include/linux/*
        \ /usr/include/arpa/*
        \ /usr/include/netinet/*
        \"
    for s in a:000
        let cmd .= ' ' . s . '*'
    endfor

    silent call LogExecute(cmd)
endfunction

command! -nargs=* -complete=file CtagsCommon
    \ call <SID>TagsCommon(<f-args>)<Bar>exe "normal <C-L>"

" Recursive create '.tags' in a directory and remove '.tags' of all
" subdirectory
function <SID>TagsRecurse(dir)
    let dirtmp = a:dir
    if a:dir != '' && a:dir[strlen(a:dir)-1] != '/'
        let dirtmp .= '/'
    endif

    silent call LogExecute("!find " . dirtmp . " -iname .tags -print0 | xargs -0 rm -f")
    let cmd = "!ctags -R --fields=+iaS --extra=+q -f "
        \ . dirtmp . ".tags " . dirtmp

    silent call LogExecute(cmd)
endfunction

command! -nargs=? -complete=file Ctags
    \ call <SID>TagsRecurse(<q-args>)<Bar>exe "normal <C-L>"

" Display all lines that contain the keyword under the cursor, jump one by
" keyed a number
map [A [I:let nr = input("Jump to [ignore when no result]: ")<Bar>exe "normal " . nr ."[\t"<CR>


" SECTION: transword <plugin> {{{1
" Author: SangYang <upperyoung@foxmail.com>
" This script looks up a word/phrase in a dictionary. User can press 
" key-shortcuts to translate word under cursor, visually selected text
" or to be asked for a word.
"
" There are several possibilities to start a translation:
"   1) move cursor over word to be translated and press <Leader>tr/tf
"   2) visually select word to be translated and press <Leader>tr/tf
"   3) press <Leader>ta to be prompted for a word
"   Memory aid: tw = (T)ranslate (W)ord, ta = (T)ranslate (A)sk for word
"               tf = (T)ranslate (F)uzzy match a word
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:tr_dictionary = s:basic_path . "common/english-chinese.dict"


" SECTION: taglist <plugin> {{{1
" Author: Yegappan Lakshmanan (yegappan AT yahoo DOT com)
"
" The "Tag List" plugin is a source code browser plugin for Vim and provides
" an overview of the structure of the programming language files and allows
" you to efficiently browse through source code files for different
" programming languages.  You can visit the taglist plugin home page for more
" information:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
nnoremap <leader>tl :TlistToggle<CR>
let Tlist_Auto_Highlight_Tag = 1
let Tlist_Auto_Update = 1
let Tlist_Compact_Format = 1
let Tlist_Display_Prototype = 1
let Tlist_Display_Tag_Scope = 1
let Tlist_Enable_Fold_Column = 1
let Tlist_Exit_OnlyWindow = 1
let Tlist_File_Fold_Auto_Close = 1
let Tlist_Process_File_Always = 1
let Tlist_Use_Right_Window = 1
let Tlist_WinWidth = 50


" SECTION: netrw <program> {{{1
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" If you want to use plugins, but for some reason don't wish to use netrw, then
" you need to avoid loading both the plugin and the autoload portions of netrw.
" You may do so by placing the following two lines in your <.vimrc>: >
let g:loaded_netrw       = 1
let g:loaded_netrwPlugin = 1

" The home directory for where bookmarks and history are saved
" (as .netrwbook and .netrwhist).
let g:netrw_home = s:basic_path . 'common'


" SECTION: NERDTree <plugin> {{{1
" Author: Marty Grenfell, scrooLoose. martin.grenfell@gmail.com
" The NERDTree is a file system explorer for the Vim editor. Using this
" plugin, users can visually browse complex directory hierarchies, quickly
" open files for reading or editing, and perform basic file system operations.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:NERDTreeWinPos = 'right'
let g:NERDTreeWinSize = 30
let g:NERDTreeShowHidden=1
nnoremap <leader>nt  :NERDTreeToggle<CR>


" SECTION: acp <plugin> {{{1
" Author: Takeshi
" With this plugin, your vim comes to automatically opens popup menu for
" completions when you enter characters or move the cursor in Insert mode. It
" won't prevent you continuing entering characters.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" AutoComplPop supports perl-completion.vim, set option to 0 or more
let g:acp_behaviorPerlOmniLength = -1


" SECTION: alternate <plugin> {{{1
" Author:  Michael Sharpe  <feline@irendi.com>
" Allow quick and easy switching between source files and corresponding
" header files. Many languages (C, C++, ada, ocaml, lex/yacc)
" have the concept of source/header files or the like.
"  <Leader>ih - switches to the file under the cursor using the :IHS command
"  <Leader>is - switches to the source file of the header file under the cursor 
"               using the :IHS command and the :A command
"  <leader>ihn - switches to the next match in the sequence.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" sfr: indicates that the path is relative to the file. 
" wdr: indicates that the directory is relative to the current working directory.
" abs: indicates the path is absolute.
"let g:alternateSearchPath = 'sfr:../source,sfr:../src,sfr:../include,sfr:../inc'


" SECTION: bufexplore  <plugin> {{{1
" Author:  https://github.com/jlanzarotta/bufexplorer
" Plugin for easily exploring (or browsing) Vim|:buffers|.
"  <Leader>be   or   :BufExplorer
"      To start exploring in the current window
"  <Leader>bt   or   :ToggleBufExplorer
"      To toggle bufexplorer on or off in the current window
"  <Leader>bs   or   :BufExplorerHorizontalSplit
"      To start exploring in a newly split horizontal window
"  <Leader>bv   or   :BufExplorerVerticalSplit
"      To start exploring in a newly split vertical window
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Override bufexplorer's default mappings
"nnoremap <silent> <F11> :BufExplorer<CR>
"nnoremap <silent> <s-F11> :ToggleBufExplorer<CR>
"nnoremap <silent> <m-F11> :BufExplorerHorizontalSplit<CR>
"nnoremap <silent> <c-F11> :BufExplorerVerticalSplit<CR>
"let g:bufExplorerDefaultHelp=0       " Do not show default help.

nnoremap <leader>be :ToggleBufExplorer<CR>


" SECTION: commentary <plugin> {{{1
" Author:  Tim Pope <http://tpo.pe/>
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:loaded_commentary = 1


" SECTION: fencview <plugin> {{{1
" Authors: Ming Bai <mbbill@gmail.com>
"          Wu Yongwei <wuyongwei@gmail.com>
" Normally, vim detects file encoding based on *fileencodings* option.
"     For example, if we set this option like this:
"     `set fileencodings=ucs-bom,GB2312,big5`
" Firstly vim try to read file bom. If there is no bom, vim will try to decode
" the file with GB2312. Unfortunately, the GB2312 and big5 have a lot of
" overlapped code-points which could lead to a big5-encoded file be decoded with
" GB2312 by mistake. Then you got mess.
"
" The **fencview.vim** uses another approach, As we know,
" take Chinese for example, the occurrence frequency of every
" character in a normal article is different. For example, '的' is a high
" frequency character which is encoded to 0xb5c4 in GB2312. However, in Big5
" 0xb5c4 is the code point for '腔' which is much less frequently used. So we
" can "guess" the encoding of a file by count up the frequently used characters.
" It is not 100% accurate but works in most cases.
"  :FencAutoDetect
"      Auto detect the file encoding.
"  :FencView
"      Open or Close the encoding list window,
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:fencview_autodetect = 1
let g:fencview_auto_patterns = '*.txt,*.htm{l\=},*.css,*.js,*.h,*.c,*.cpp'
nnoremap <leader>fv :FencView<CR>
nnoremap <leader>fva :FencAutoDetect<CR>


" SECTION: grep <plugin> {{{1
" Author: Yegappan Lakshmanan  (yegappan AT yahoo DOT com)
" The grep plugin integrates grep like utilities (grep, fgrep, egrep, agrep,
" findstr, silver searcher, ack, ripgrep, git grep, sift, platinum searcher and
" universal code grep) with Vim and allows you to search for a pattern in one or
" more files and jump to them.
"  :Grep          - Search for the specified pattern in the specified files
"  :GrepAdd       - Same as ":Grep" but adds the results to the current results
"  :Rgrep         - Run recursive grep
"  :RgrepAdd      - Same as ":Rgrep" but adds the results to the current results
"  :GrepBuffer    - Search for a pattern on all open buffers
"  :GrepBufferAdd - Same as ":GrepBuffer" but adds the results to the current list
"  :Bgrep         - Same as :GrepBuffer
"  :BgrepAdd      - Same as :GrepBufferAdd
"  :GrepArgs      - Search for a pattern on all the Vim argument filenames (:args)
"  :GrepArgsAdd   - Same as ":GrepArgs" but adds the results to the current list
"  :Fgrep         - Run fgrep
"  :FgrepAdd      - Same as ":Fgrep" but adds the results to the current list
"  :Rfgrep        - Run recursive fgrep
"  :RfgrepAdd     - Same as ":Rfgrep" but adds the results to the current list
"  :Egrep         - Run egrep
"  :EgrepAdd      - Same as ":Egrep" but adds the results to the current list
"  :Regrep        - Run recursive egrep
"  :RegrepAdd     - Same as ":Regrep" but adds the results to the current list
"  :Findstr       - Search for a pattern in files. Available only on MS-Windows.
"  :FindstrAdd    - Same as ":Findstr" but adds the results to the current list
"  :Agrep         - Run agrep
"  :AgrepAdd      - Same as ":Agrep" but adds the results to the current list
"  :Ragrep        - Run recursive agrep
"  :RagrepAdd     - Same as ":Ragrep" but adds the results to the current list
"  :Ag            - Run the silver searcher (ag)
"  :AgAdd         - Same as ":Ag" but adds the results to the current list
"  :Ack           - Run ack
"  :AckAdd        - Same as ":Ack" but adds the results to the current list
"  :Rg            - Run ripgrep (rg)
"  :RgAdd         - Same as ":Rg" but adds the results to the current list
"  :Gitgrep       - Run git grep
"  :GitgrepAdd    - Same as ":Gitgrep" but adds the results to the current list
"  :Sift          - Run sift
"  :SiftAdd       - Same as ":Sift" but adds the results to the current list
"  :Ptgrep        - Run the platinum searcher (pt)
"  :PtgrepAdd     - Same as ":Ptgrep" but adds the results to the current list
"  :Ucgrep        - Run the Universal code grep (ucg)
"  :UcgrepAdd     - Same as ":Ucgrep" but adds the results to the current list
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" invokes the :Grep command to search for the keyword under the cursor
nnoremap <F3> :Grep<CR>

" prompted for the files in which to search for the pattern
let Grep_Default_Filelist = '*.*'

" ignore case distinctions
"let Grep_Options = '-i'

" the list of directories to skip while doing recursive searches
"let Grep_Skip_Dirs = 'dir1 dir2 dir3'

" the list of files to skip while doing recursive searches
"let Grep_Skip_Files = '*.bak *~'


" SECTION: matchit <plugin> {{{1
" Extended "%" matching
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"let b:match_ignorecase = 1


" SECTION: mimicpak <plugin> {{{1
" A set of colorschemes which were converted from other editors
" and IDEs and that share some common tweaking options.
" Note that most of the colorschemes are only for |gvim|, this is so,
" because of time reasons and available number of colors.
"     ,--------------------,--------,-------,-------------. ~
"     |  Colorscheme       |  gVim  |  Vim  |  'bg' type  | ~
"     +--------------------+--------+-------+-------------+ ~
"     | |anokha.vim|       |  Yes   |  No   |  DJ         |
"     | |astroboy.vim|     |  Yes   |  No   |  Dark       |
"     | |bigbang.vim|      |  Yes   |  Yes  |  Dark       |
"     | |deepblue.vim|     |  Yes   |  No   |  Dark       |
"     | |dejavu.vim|       |  Yes   |  Yes  |  Dark/Light |
"     | |gaea.vim|         |  Yes   |  No   |  Light      |
"     | |greyhouse.vim|    |  Yes   |  Yes  |  Light      |
"     | |imperial.vim|     |  Yes   |  Yes  |  Light      |
"     | |intellij.vim|     |  Yes   |  Yes  |  Light      |
"     | |masmed.vim|       |  Yes   |  No   |  Dark       |
"     | |mickeysoft.vim|   |  Yes   |  No   |  Light      |
"     | |omen.vim|         |  Yes   |  Yes  |  Light      |
"     | |paradox.vim|      |  Yes   |  No   |  Dark       |
"     | |psclone.vim|      |  Yes   |  No   |  Dark       |
"     | |scame.vim|        |  Yes   |  Yes  |  Light      |
"     | |vimhut.vim|       |  Yes   |  No   |  Dark/Light |
"     | |zendnb.vim|       |  Yes   |  Yes  |  Dark       |
"     '--------------------'--------'-------'-------------'
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" You can avoid loading the menu by setting the variable
let g:loaded_mimicpak = 1


" SECTION: minibufexpl <plugin> {{{1
" Mini Buffer Explorer
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
map <Leader>mb :MBEToggle<CR>
map <Leader>mbo :MBEOpen<CR>
map <Leader>mbc :MBEClose<CR>
map <Leader>mba :MBEToggleAll<CR>
map <Leader>mbao :MBEOpenAll<CR>
map <Leader>mbac :MBECloseAll<CR>

let g:miniBufExplMaxSize = 5


" SECTION: project <plugin> {{{1
" Author: Aric Blumer
" Plugin for managing multiple projects with multiple sources.
" To set up a list of frequently-accessed files for easy navigation. 
" The list of files will be displayed in a window on the left side
" of the Vim window.
" These scripts can modify the environment to include compilers
" in $PATH. This makes it very easy to use quickfix with multiple projects
" that use different environments.
"
" 1) Each Project Entry has this form:
"    project_entry ::=
"      <Description>={projpath} [{options}] {
"         [ filename ]
"         [ project_entry ]
"      }
"    {options} is one or more of the following (on the same line):
"         CD={path}
"         in={filename}
"         out={filename}
"         filter="{pat}"
"         flags={flag}
" 2) mappings
" (This mapping is actually <LocalLeader>, and the default is \)
" Map   Action
" \r    Refreshes the Project fold that the cursor is in by placing in the
"       fold all the files that match the filter.
" \R    Executes \r recursively in the current fold and all folds below.
" \c    Creates a Project fold entry.
" \C    Creates a Project fold entry like \c, but recursively includes all the
"       subdirectories.
" <Return>
"       Select a file to open in the |CTRL-W_p| window or in a new window.
"       If the cursor is on a fold, open or close it.
" <RightMouse>
" <space>
"       Toggle the width of the Project Window by g:proj_window_increment
" \i    Display what the cursor's project inherits.
" \l    Load all the files in the current Project level into Vim.
"       While files are being loaded, you may press any key to stop.
" \L    Load all the files in the current Project and all Subprojects into
"       Vim. (wouldn't suggest)
" \w    Wipe all the files in the current Project level from Vim. 
"       (If files are modified, they will be saved first.)
" \W    Wipe all the files in the current Project and all Subprojects from
"       Vim.
" \g    Grep all the files in the current Project level.
" \G    Grep all the files in the current Project level and all Subprojects.
" \e    Set up the Environment for the Project File as though you had selected
"       it with <Return>.  This allows you to do a \e and a :make without
"       having to open any files in the project.
" \E    Explore the directory of the project the
"       cursor is in.  Does not work with netrw.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" When the 'g' flag is present in g:proj_flags,
" <F12> toggles the Project Window open and closed.
" You may remap this toggle function.
nmap <Leader>p <Plug>ToggleProject

" invoke :Project on only one file at a time
nmap <Leader>po :Project 

" If you wish to change the Project File, do a :bwipe in the Project Buffer,
" Everything related to the buffer is lost.
nnoremap <Leader>pc :bwipeout 

let g:proj_flags = 'imstbg'


" SECTION: surround <plugin> {{{1
" Author: Tim Pope <http://tpo.pe/>
" This plugin is a tool for dealing with pairs of "surroundings."
" (Examples of surroundings include parentheses, quotes, and HTML tags.)
"   Old text                  Command     New text ~
"   "Hello *world!"           ds"         Hello world!
"   (123+4*56)/2              ds)         123+456/2
"   <div>Yo!*</div>           dst         Yo!
"   "Hello *world!"           cs"'        'Hello world!'
"   "Hello *world!"           cs"<q>      <q>Hello world!</q>
"   (123+4*56)/2              cs)]        [123+456]/2
"   (123+4*56)/2              cs)[        [ 123+456 ]/2
"   <div>Yo!*</div>           cst<p>      <p>Yo!</p>
"   Hello w*orld!             ysiw)       Hello (world)!
"   if *x>3 {                 ysW(        if ( x>3 ) {
"   my $str = *whee!;         vllllS'     my $str = 'whee!';
" 
" (*yss* operates on the current line, ignoring leading whitespace.)
"   Hello w*orld!             yssB        {Hello world!}
" 
" (*yS* and *ySS* which indent the surrounded text)
" (and place it on a line of its own.)
"   *Hello world!             ySW{        {
"                                             Hello
"                                         } world!
"   H*ello world!             ySS{
"                                         {
"                                             Hello world!
"                                         }
" (In visual mode, a simple "S" with an argument wraps the selection.)
" (This is referred to as the *vS* mapping)
"   H*ell*o world!             vS(        H( ell )o world!
"   H*ell*o world!             vgS(       H(
"                                             ell
"                                         )o world!
" (Finally, an experimental insert mode mapping on <C-G>s.)
"   hello*                     <C-G>s]    hello[]
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" SECTION: winmanager <plugin> {{{1
" Author: Srinath Avadhanula (srinath@fastmail.fm)
" winmanager.vim is a plugin which implements a classical windows type IDE in
" Vim-6.0, where the directory and buffer browsers are displayed in 2 windows on
" the left and the current editing is done on the right.
"   1) File Explorer plugin
"   This plugin displays the current directory. Its a modification of the standard
"   explorer.vim which ships with vim6.0. The following keyboard shortcuts are
"   available with this plugin:
"   <enter>    if on a directory, enters it and displays it in the same
"              area. If on a file, then opens it in the File Editing Area.
"   <tab>      open the file or directory in a new window in the FileEditing area. 
"   c          change the pwd to the directory currently displayed 
"   C          change the currently displayed directory to pwd (converse of c)
"   s          select sort field (size, date, name) 
"   r          reverse direction of sort 
"   f          add current directory to list of favorites.
"   R          rename file 
"   D          delete file (or range of files in visual mode)
"   -          move up one level
"   <F5>       refresh the file list
"   2) Buffer Explorer plugin
"   (NOTE: In addition to those shortcuts, winmanager adds the following)
"   <tab>      Opens the buffer under the cursor in a split window even if
"              the current buffer is not modified.
"   3) File Editing Area
"   The area where normal editing takes place. The commands in the File Explorer
"   and Buffer Explorer shouldnt affect the layout of the windows here.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"  You can avoid loading this plugin by setting the "loaded_winmanager" variable
"let loaded_winmanager = 1

" winmanager only recognizes plugins whose name appears in the global variable.
" When a window contains multiple explorers, then the user can cycle between
" them by pressing <c-n> or <c-p>. 
"let g:winManagerWindowLayout = 'FileExplorer,TagsExplorer|BufExplorer'

" toggles the visibility of winmanager
"map <Leader>wm :WMToggle<cr> 
"map <Leader>wmb :BottomExplorerWindow<cr>
"map <Leader>wmf :FirstExplorerWindow<cr>


" SECTION: ScrollColors<plugin> {{{1
" Author: Yakov Lerner <iler_ml@fastmail.fm>
" This is colorscheme Scroller/Chooser/Browser.
" With this plugin, you walk through installed 
" colorschemes using arrow keys.
"   1  Type :SCROLLCOLOR
"   2. Use arrows to scroll thgough colorschemes.
"   3. When done, press Esc to exit. You will be prompted wether to 
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" SECTION: NERD_commenter <plugin> {{{1
" Author: https://github.com/scrooloose/nerdcommenter
" The NERD commenter provides many different commenting operations and styles
" which are invoked via key mappings and a menu. These operations are available
" for most filetypes.
"   ,cc |NERDComComment|
"       Comment out the current line or text selected in visual mode.
"   ,cn |NERDComNestedComment|
"       Same as ,cc but forces nesting.
"   ,c<space> |NERDComToggleComment|
"       Toggles the comment state of the selected line(s). 
"   ,cm |NERDComMinimalComment|
"       Comments the given lines using only one set of multipart delimiters.
"   ,ci |NERDComInvertComment|
"       Toggles the comment state of the selected line(s) individually.
"   ,cs |NERDComSexyComment|
"       Comments out the selected lines 'sexily'
"   ,cy |NERDComYankComment|
"       Same as ,cc except that the commented line(s) are yanked first.
"   ,c$ |NERDComEOLComment|
"       Comments the current line from the cursor to the end of line.
"   ,cA |NERDComAppendComment|
"       Adds comment delimiters to the end of line and goes into insert mode
"       between them.
"   |NERDComInsertComment|
"       Adds comment delimiters at the current cursor position and inserts between.
"       Disabled by default.
"   ,ca |NERDComAltDelim|
"       Switches to the alternative set of delimiters.
"   ,cl
"   ,cb |NERDComAlignedComment|
"       Same as |NERDComComment| except that the delimiters are aligned down the
"       left side (,cl) or both sides (,cb).
"   ,cu |NERDComUncommentLine|
"       Uncomments the selected line(s).
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let NERDSpaceDelims = 1


" SECTION: echofunc <plugin> {{{1
" Authors: Ming Bai <mbbill AT gmail DOT com>,
"          Wu Yongwei <wuyongwei AT gmail DOT com>
" Echo the function declaration in the command line for C/C++,
" as well as other languages that ctags supports.
" 
" When you type '(' after a function name in insert mode,
" the function declaration will be displayed in the command line automatically.
" Use Alt+- and Alt+= (configurable via EchoFuncKeyPrev and EchoFuncKeyNext)
" to cycle between function declarations (if exists).
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:EchoFuncKeyNext = '<M-=>'
let g:EchoFuncKeyPrev = '<M-->'


" SECTION: genutils <plugin> {{{1
" Author: Hari Krishna Dara (hari_vim at yahoo dot com)
" genutils: Useful buffer, file and window related functions.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" SECTION: lookupfile <plugin> {{{1
" Author: Hari Krishna Dara (hari.vim at gmail dot com)
" Lookupfile is a very simple approach to opening files by typing a pattern to
" represent the file you are looking for, and selecting a file from the completion
" dropdown to open in the current Vim session.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:LookupFile_RecentFileListSize = 30
let g:LookupFile_TagExpr = string('./filenametags')
let g:LookupFile_MinPatLength = 2
let g:LookupFile_PreservePatternHistory = 1
let g:LookupFile_AlwaysAcceptFirst = 1
let g:LookupFile_AllowNewFiles = 0

function <SID>LookupTags(dir)
        "find . \( -name .svn -o -wholename ./classes \) -prune -o -not -iregex '.*\.\(jar\|gif\|jpg\|class\|exe\|dll\|pdd\|sw[op]\|xls\|doc\|pdf\|zip\|tar\|ico\|ear\|war\|dat\).*' -type f -printf "%f\t%p\t1\n" \
    let cmd = "!find . -type f -printf " . "'\\%f\\t\\%p\\t1\\n' > ./filenametags"
    echomsg cmd
    execute cmd
endfunction

command! -nargs=? -complete=file LookupTags
    \ call <SID>LookupTags(<q-args>)<Bar>exe "normal <C-L>"

nmap <unique> <Leader>lf <Plug>LookupFile
imap <unique> <Leader>lf <C-O><Plug>LookupFile
nmap <unique> <leader>lft :LUTags<cr>
nmap <unique> <leader>lfb :LUBufs<cr>
nmap <unique> <leader>lfw :LUWalk<cr>


" SECTION: supertab <plugin> {{{1
" Author: Eric Van Dewoestine <ervandew@gmail.com>
"         Original concept and versions up to 0.32 written by
"         Gergely Kontra <kgergely@mcl.hu>
" Supertab is a plugin which allows you to perform all your insert completion
" (|ins-completion|) using the tab key.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:SuperTabDefaultCompletionType = "context"
let g:SuperTabNoCompleteBefore = ['']
let g:SuperTabNoCompleteAfter = ['^', '\s', ',']
"let g:SuperTabMappingForward = '<Space>'
"let g:SuperTabMappingBackward = '<S-C-Space>'


" SECTION: mru <plugin> {{{1
" Author: Yegappan Lakshmanan  (yegappan AT yahoo DOT com)
" The Most Recently Used (MRU) plugin provides an easy access to a list of
" recently opened/edited files in Vim. This plugin automatically stores the
" file names as you open/edit them in Vim.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let MRU_File = s:basic_path . 'common/vim_mru_files'
nmap <unique> <Leader>mr :MRU<CR>


" SECTION: srcexpl <plugin> {{{1
" Author: Wenlong Che <wenlong.che@gmail.com>
"         Jonathan Lai <laiks.jonathan@gmail.com>
" SrcExpl (Source Explorer) is a source code explorer that provides context for
" the currently selected keyword by displaying the function or type definition
" or declaration in a separate window.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
nmap <unique> <Leader>se :SrcExplToggle<CR>
"nmap <C-I> <C-W>j:call g:SrcExpl_Jump()<CR> 
"nmap <C-O> :call g:SrcExpl_GoBack()<CR> 


" SECTION: visualmark <plugin> {{{1
" Author: brian.wang.0721@gmailcom
" This script uses Vim's "sign" capability to provide visual marks, similar to 
" UltraEdit's bookmark. If you do not like the highlighting scheme, you could
" change "SignColor" in the script.
" USAGE:
"   ,vm        toggle sign
"   ,vn        goto next sign
"   ,vp        goto_prev_sign
"   ,va        remove all signs
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" SECTION: ShowMarks <plugin> {{{1
" Author: Anthony Kruize <trandor@labyrinth.net.au>
"         Michael Geddes <michaelrgeddes@optushome.com.au>
" ShowMarks provides a visual representation of |marks| local to a buffer.
"  <Leader>mt   - Toggles ShowMarks on and off.
"  <Leader>mo   - Forces ShowMarks on.
"  <Leader>mc   - Clears the mark at the current line.
"  <Leader>ma   - Clears all marks in the current buffer.
"  <Leader>mm   - Places the next available mark on the current line.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" This option enables or disables ShowMarks on startup
let showmarks_enable = 0

" This option specifies which marks will be shown and in which order if placed on the same line.
"let showmarks_include = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

" Ignore help, quickfix, non-modifiable buffers
let showmarks_ignore_type = "hmpq"

" This option defines how the marks will be displayed.
let showmarks_textlower = " "
let showmarks_textupper = " "
let showmarks_textother = " "

" whether the entire line will be highlighted.
let showmarks_hlline_lower = 0
let showmarks_hlline_upper = 0 
let showmarks_hlline_other = 0


" SECTION: xmledit <plugin> {{{1
" Author: devin@tritarget.com
" A filetype plugin to help edit XML and SGML documents.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" SECTION: ctrlp <plugin> {{{1
" Author: kien
" Full path fuzzy file, buffer, mru, tag, ... finder with an intuitive interface.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use this option to change the mapping to invoke CtrlP in |Normal| mode: >
let g:ctrlp_map = '<c-p>'

" Set the default opening command to use when pressing the above mapping: >
let g:ctrlp_cmd = 'CtrlP'

" Set this to 1 to set searching by filename (as opposed to full path).
" Can be toggled on/off by pressing <c-d> inside the prompt.
let g:ctrlp_by_filename = 0

" Set this to 1 to set regexp search as the default.
" Can be toggled on/off by pressing <c-r> inside the prompt.
let g:ctrlp_regexp = 0

" When starting up, CtrlP sets its local working directory according to this
" variable: >
let g:ctrlp_working_path_mode = 'ar'

" Enable/Disable per-session caching: >
"   0 - Disable caching.
"   1 - Enable caching.
"   n - When bigger than 1, disable caching and use the number as the limit to
"       enable caching again.
" Note: you can quickly purge the cache by pressing <F5> while inside CtrlP.
let g:ctrlp_use_caching = 1

" Set the directory to store the cache files: >
let g:ctrlp_cache_dir = s:basic_path . 'common/cache_ctrlp'

" Set this to 1 if you want CtrlP to scan for dotfiles and dotdirs: >
let g:ctrlp_show_hidden = 0

" Use Vim's 'wildignore' to exclude files and directories from the results.
" Note #1: the `*/` in front of each directory glob is required.
" Note #2: |wildignore| influences the result of |expand()|, |globpath()| and
" |glob()| which many plugins use to find stuff on the system (e.g. VCS related
" plugins look for .git/, .hg/,... some other plugins look for external *.exe
" tools on Windows). So be a little mindful of what you put in your |wildignore|.
"set wildignore+=*/.git/*,*/.hg/*,*/.svn/*        " Linux/MacOSX
"set wildignore+=*\\.git\\*,*\\.hg\\*,*\\.svn\\*  " Windows ('noshellslash')

" Use this to customize the mappings inside CtrlP's prompt to your liking. You
" only need to keep the lines that you've changed the values (inside [])
" Note: if pressing <bs> moves the cursor one character to the left instead of
" deleting a character for you, add this to your |.vimrc| to disable the plugin's
" default <c-h> mapping:
"     let g:ctrlp_prompt_mappings = { 'PrtCurLeft()': ['<left>', '<c-^>'] }
"let g:ctrlp_prompt_mappings = {
"    \ 'PrtBS()':              ['<bs>', '<c-]>'],
"    \ 'PrtDelete()':          ['<del>'],
"    \ 'PrtDeleteWord()':      ['<c-w>'],
"    \ 'PrtClear()':           ['<c-u>'],
"    \ 'PrtSelectMove("j")':   ['<c-j>', '<down>'],
"    \ 'PrtSelectMove("k")':   ['<c-k>', '<up>'],
"    \ 'PrtSelectMove("t")':   ['<Home>', '<kHome>'],
"    \ 'PrtSelectMove("b")':   ['<End>', '<kEnd>'],
"    \ 'PrtSelectMove("u")':   ['<PageUp>', '<kPageUp>'],
"    \ 'PrtSelectMove("d")':   ['<PageDown>', '<kPageDown>'],
"    \ 'PrtHistory(-1)':       ['<c-n>'],
"    \ 'PrtHistory(1)':        ['<c-p>'],
"    \ 'AcceptSelection("e")': ['<cr>', '<2-LeftMouse>'],
"    \ 'AcceptSelection("h")': ['<c-x>', '<c-cr>', '<c-s>'],
"    \ 'AcceptSelection("t")': ['<c-t>'],
"    \ 'AcceptSelection("v")': ['<c-v>', '<RightMouse>'],
"    \ 'ToggleFocus()':        ['<s-tab>'],
"    \ 'ToggleRegex()':        ['<c-r>'],
"    \ 'ToggleByFname()':      ['<c-d>'],
"    \ 'ToggleType(1)':        ['<c-f>', '<c-up>'],
"    \ 'ToggleType(-1)':       ['<c-b>', '<c-down>'],
"    \ 'PrtExpandDir()':       ['<tab>'],
"    \ 'PrtInsert("c")':       ['<MiddleMouse>', '<insert>'],
"    \ 'PrtInsert()':          ['<c-\>'],
"    \ 'PrtCurStart()':        ['<c-a>'],
"    \ 'PrtCurEnd()':          ['<c-e>'],
"    \ 'PrtCurLeft()':         ['<c-h>', '<left>', '<c-^>'],
"    \ 'PrtCurRight()':        ['<c-l>', '<right>'],
"    \ 'PrtClearCache()':      ['<F5>'],
"    \ 'PrtDeleteEnt()':       ['<F7>'],
"    \ 'CreateNewFile()':      ['<c-y>'],
"    \ 'MarkToOpen()':         ['<c-z>'],
"    \ 'OpenMulti()':          ['<c-o>'],
"    \ 'PrtExit()':            ['<esc>', '<c-c>', '<c-g>'],
"    \ }



" SECTION: Deinitialization {{{1
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" Restore 'cpoptions' option from Vim default value to previous value
let &cpoptions = s:save_cpo
unlet s:save_cpo

" vim: set sw=4 ts=4 sts=4 et tw=78 foldlevel=1 foldmethod=marker:
